import { iframeLoad } from '@/components/iframe'
import { deepCopy } from '@/utils'
import { closeTag } from '@/utils/outerUtils'

// 复制route
function copyRoute(route) {
  return {
    path: route.path,
    meta: deepCopy(route.meta),
    query: deepCopy(route.query),
    params: deepCopy(route.params),
    fullPath: route.fullPath,
    name: route.name
  }
}

const state = {
  visitedViews: [],
  visitedQueue: [], // 记录访问先后数据队列
  cachedViews: [],
  iframeLink: [],
  destroyComponent: null // 销毁组件
}

const mutations = {
  ADD_VISITED_VIEW: (state, view) => {
    // 首页特殊处理
    if (view.name === 'HomePage' && state.visitedViews.some(v => v.name === view.name)) return
    if (state.visitedViews.some(v => v.fullPath === view.fullPath)) return
    state.visitedViews.push(
      Object.assign({}, copyRoute(view), {
        title: view.meta.title || view.query.name || '无标题'
      })
    )
    if (view.fullPath.includes('/myiframe')) {
      state.iframeLink.push(
        Object.assign({}, copyRoute(view), {
          link: iframeLoad(view)
        })
      )
    }
  },
  ADD_CACHED_VIEW: (state, view) => {
    if (state.cachedViews.includes(view.name)) return
    if (!view.meta.noCache) {
      state.cachedViews.push(view.name)
    }
  },

  DEL_VISITED_VIEW: (state, view) => {
    const visitedQueueFullPath = state.visitedQueue.map(e => e.fullPath)
    for (const [i, v] of state.visitedViews.entries()) {
      if (v.fullPath === view.fullPath) {
        state.visitedViews.splice(i, 1)
        // 从visitedQueue中删除已经关闭的标签
        const n = visitedQueueFullPath.indexOf(view.fullPath)
        if (n > -1) {
          state.visitedQueue.splice(n, 1)
        }
        break
      }
    }
    for (const [j, v] of state.iframeLink.entries()) {
      if (v.fullPath === view.fullPath) {
        state.iframeLink.splice(j, 1, '')
        break
      }
    }
  },
  DEL_CACHED_VIEW: (state, view) => {
    // 会导致页面内容更新
    // for (const i of state.cachedViews) {
    //   if (i === view.name) {
    //     const index = state.cachedViews.indexOf(i)
    //     state.cachedViews.splice(index, 1)
    //     break
    //   }
    // }
    if (state.destroyComponent instanceof Function) {
      state.destroyComponent(view)
    }
  },

  DEL_OTHERS_VISITED_VIEWS: (state, view) => {
    state.visitedViews = state.visitedViews.filter(v => {
      return v.meta.affix || v.fullPath === view.fullPath
    })
    state.iframeLink = state.iframeLink.filter(v => {
      return v.meta.affix || v.fullPath === view.fullPath
    })
    // 删除其他访问信息
    state.visitedQueue = state.visitedQueue.filter(v => {
      return v.meta.affix || v.fullPath === view.fullPath
    })
  },
  DEL_OTHERS_CACHED_VIEWS: (state, view) => {
    for (const i of state.cachedViews) {
      if (i === view.name) {
        const index = state.cachedViews.indexOf(i)
        state.cachedViews = state.cachedViews.slice(index, index + 1)
        break
      }
    }
    if (state.destroyComponent instanceof Function) {
      state.destroyComponent([view], 'other')
    }
  },

  DEL_ALL_VISITED_VIEWS: state => {
    // keep affix tags
    const affixTags = state.visitedViews.filter(tag => tag.meta.affix)
    state.visitedViews = affixTags
    state.iframeLink = []
    state.visitedQueue = state.visitedQueue.filter(v => {
      return v.meta.affix
    })
  },
  DEL_ALL_CACHED_VIEWS: state => {
    state.cachedViews = []
    if (state.destroyComponent instanceof Function) {
      state.destroyComponent(state.visitedQueue.filter(v => {
        return v.meta.affix
      }), 'other')
    }
  },

  UPDATE_VISITED_VIEW: (state, view) => {
    for (let v of state.visitedViews) {
      if (v.fullPath === view.fullPath) {
        v = Object.assign(v, copyRoute(view))
        break
      }
    }
  },

  // keep-alive相关
  UPDATE_KEEP_ALIVE: (state, v = null) => {
    state.destroyComponent = v || (() => ({}))
  },

  // 访问先后数据队列更新
  ADD_VISITED_QUEUE: (state, v) => {
    if (v.name === null) {
      return
    }
    if (v.fullPath.includes('/login') || v.fullPath.includes('/redirect') || /^\/\d+$/.test(v.fullPath)) {
      return
    }
    for (let i = 0; i < state.visitedQueue.length; i++) {
      const item = state.visitedQueue[i]
      if (v.fullPath === item.fullPath) {
        state.visitedQueue.splice(i, 1)
        break
      }
    }
    state.visitedQueue.push(copyRoute(v))
  },
  DEL_VISITED_QUEUE: (state, v) => {
    if (v.name === null) {
      return
    }
    for (let i = 0; i < state.visitedQueue.length; i++) {
      const item = state.visitedQueue[i]
      if (v.fullPath === item.fullPath) {
        state.visitedQueue.splice(i, 1)
        break
      }
    }
  }
}

const actions = {
  addView({ dispatch }, view) {
    dispatch('addVisitedView', view)
    dispatch('addCachedView', view)
  },
  addVisitedView({ commit }, view) {
    commit('ADD_VISITED_VIEW', view)
    // 添加访问数据
    commit('ADD_VISITED_QUEUE', view)
  },
  addCachedView({ commit }, view) {
    commit('ADD_CACHED_VIEW', view)
  },

  delView({ dispatch, state }, view) {
    return new Promise((resolve, reject) => {
      dispatch('delVisitedView', view)
      dispatch('delCachedView', view)
      if (window.top !== window) {
        closeTag(view.fullPath)
        reject('外部系统不打开临近标签')
        return
      }
      resolve({
        visitedViews: [...state.visitedViews],
        cachedViews: [...state.cachedViews],
        visitedQueue: [...state.visitedQueue]
      })
    })
  },
  delVisitedView({ commit, state }, view) {
    return new Promise(resolve => {
      commit('DEL_VISITED_VIEW', view)
      // 删除访问数据
      commit('DEL_VISITED_QUEUE', view)
      resolve([...state.visitedViews])
    })
  },
  delCachedView({ commit, state }, view) {
    return new Promise(resolve => {
      commit('DEL_CACHED_VIEW', view)
      resolve([...state.cachedViews])
    })
  },

  delOthersViews({ dispatch, state }, view) {
    return new Promise(resolve => {
      dispatch('delOthersVisitedViews', view)
      dispatch('delOthersCachedViews', view)
      resolve({
        visitedViews: [...state.visitedViews],
        cachedViews: [...state.cachedViews]
      })
    })
  },
  delOthersVisitedViews({ commit, state }, view) {
    return new Promise(resolve => {
      commit('DEL_OTHERS_VISITED_VIEWS', view)
      resolve([...state.visitedViews])
    })
  },
  delOthersCachedViews({ commit, state }, view) {
    return new Promise(resolve => {
      commit('DEL_OTHERS_CACHED_VIEWS', view)
      resolve([...state.cachedViews])
    })
  },

  delAllViews({ dispatch, state }, view) {
    return new Promise(resolve => {
      dispatch('delAllVisitedViews', view)
      dispatch('delAllCachedViews', view)
      resolve({
        visitedViews: [...state.visitedViews],
        cachedViews: [...state.cachedViews]
      })
    })
  },
  delAllVisitedViews({ commit, state }) {
    return new Promise(resolve => {
      commit('DEL_ALL_VISITED_VIEWS')
      resolve([...state.visitedViews])
    })
  },
  delAllCachedViews({ commit, state }) {
    return new Promise(resolve => {
      commit('DEL_ALL_CACHED_VIEWS')
      resolve([...state.cachedViews])
    })
  },

  updateVisitedView({ commit }, view) {
    commit('UPDATE_VISITED_VIEW', view)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
